package com.neomanager.admin.web;

import java.util.ArrayList;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import sun.misc.BASE64Encoder;

import com.neomanager.admin.dao.AdminDao;
import com.neomanager.admin.dao.AuthDao;
import com.neomanager.login.model.AdminInfo;
import com.util.JspMaker;
import com.util.SHA256;
import com.util.UtilCommon;

@Controller
@SuppressWarnings("restriction")
@SessionAttributes("adminInfo")
public class AdminController
{
	private final Logger logger = Logger.getLogger(this.getClass());
	@Resource(name="AdminDao")
	AdminDao admin;
	@Resource(name="AuthDao")
	AuthDao auth;

	/**
	 * 관리자 목록
	 */
	@RequestMapping(value = "/admin/adminmng_list.do", method = RequestMethod.GET)
	public String listAdminmng(@RequestParam Map<String, Object> commandMap, Model model,
			HttpServletRequest request, HttpServletResponse response)
	{
		logger.info("관리자 목록.");
	    HttpSession session = request.getSession();
	    AdminInfo aInfo = (AdminInfo) session.getAttribute( "adminInfo" );
		String id = aInfo.getAdmin_id();
		String menuFile = "../menu/" + id + "_menu.jsp";

		// 현재 페이지
		int page = 1;
		if (commandMap.get("page") != null)
			page = Integer.parseInt(commandMap.get("page").toString());

		// 페이지당 목록 수
		int pageCount = 10;

		// 시작번호
		int startNo = (page - 1) * pageCount;

		commandMap.put("page", page);
		commandMap.put("pageCount", pageCount);
		ArrayList<Map<String, Object>> listMap = admin.selectAdminInfo(commandMap);

		// 총 갯수
		int totalCount = 0;
		if ( listMap != null && listMap.size() > 0 )
		{
			Map<String, Object> rs = listMap.get(0);
			totalCount = Integer.parseInt( rs.get("TOTALCOUNT").toString() );
		}
		startNo = totalCount - startNo;

		// 페이징 처리
		if (totalCount > 0)
		{
			UtilCommon util = new UtilCommon();
			// 총게시물수, 페이지당 목록수, 현재페이지, 블럭당 나타낼 페이지 수
			util.setPage(totalCount, pageCount, page, 10);
			commandMap.put("totalCount", totalCount);
			commandMap.put("totalPage", util.getTotalPage());
			commandMap.put("startPage", util.getStartPage());
			commandMap.put("endPage", util.getEndPage());
			commandMap.put("startNo", startNo);
		}

		model.addAttribute("menuinclude", menuFile);
		model.addAttribute("adminInfo", aInfo);
		model.addAttribute("commandMap", commandMap);
		model.addAttribute("listMap", listMap);

		return "admin/adminmng_list";
	}

	/**
	 * 관리자 등록 화면
	 */
	@RequestMapping(value = "/admin/adminmng_write.do", method = RequestMethod.GET)
	public String writeAdminmng(@RequestParam Map<String, Object> commandMap, Model model,
			HttpServletRequest request, HttpServletResponse response)
	{
		logger.info("관리자 등록 화면.");
	    HttpSession session = request.getSession();
	    AdminInfo aInfo = (AdminInfo) session.getAttribute( "adminInfo" );
		String id = aInfo.getAdmin_id();
		String menuFile = "../menu/" + id + "_menu.jsp";

		model.addAttribute("menuinclude", menuFile);
		model.addAttribute("adminInfo", aInfo);

		return "admin/adminmng_write";
	}

	/**
	 * 관리자 수정 화면
	 */
	@RequestMapping(value = "/admin/adminmng_edit.do", method = RequestMethod.GET)
	public String editAdminmng(@RequestParam Map<String, Object> commandMap, Model model,
			HttpServletRequest request, HttpServletResponse response)
	{
		logger.info("관리자 수정 화면.");
	    HttpSession session = request.getSession();
	    AdminInfo aInfo = (AdminInfo) session.getAttribute( "adminInfo" );
		String id = aInfo.getAdmin_id();
		String menuFile = "../menu/" + id + "_menu.jsp";

		Map<String, Object> listMap = admin.selectAdminInfoById(commandMap);

		model.addAttribute("menuinclude", menuFile);
		model.addAttribute("adminInfo", aInfo);
		model.addAttribute("listMap", listMap);

		return "admin/adminmng_edit";
	}


	/**
	 * 관리자 등록/수정/삭제 처리
	 */
	@RequestMapping(value = "/admin/adminmng_proc.do", method = RequestMethod.POST)
	public String processAdminmng(@RequestParam Map<String, Object> commandMap, Model model,
			HttpServletRequest request, HttpServletResponse response)
	{
		logger.debug("관리자 등록/수정/삭제 처리.");

		String root = request.getSession().getServletContext().getRealPath(""); //servelt rootpath 구하기
		String userId = commandMap.get("admin_id").toString();

		if(commandMap.get("mode").toString().equals("write"))
		{
			String sys_id = UtilCommon.idMake("");
			commandMap.put("sys_id", sys_id);

			// 비밀번호 암호화
			String admin_pw = commandMap.get("admin_pw").toString();

			SHA256 s = new SHA256( admin_pw.getBytes() );
			BASE64Encoder Base64Encoder = new BASE64Encoder();
			admin_pw = Base64Encoder.encode(s.GetHashCode());
			commandMap.put("admin_pw", admin_pw);

			admin.insertAdminInfo(commandMap);

			//default JSP_menu 생성
			String content = "String[][] menuArr = {";

			JspMaker jspmaker = new JspMaker();
			jspmaker.makeJspFile(content, userId, root);
		}
		else if(commandMap.get("mode").toString().equals("edit"))
		{
			// 비밀번호 암호화
			String admin_pw = commandMap.get("admin_pw").toString();
			if (admin_pw !=  null && !admin_pw.equals(""))
			{
				SHA256 s = new SHA256( admin_pw.getBytes() );
				BASE64Encoder Base64Encoder = new BASE64Encoder();
				admin_pw = Base64Encoder.encode(s.GetHashCode());
				commandMap.put("admin_pw", admin_pw);
			}
			admin.updateAdminInfo(commandMap);
		}
		else if(commandMap.get("mode").toString().equals("delete"))
		{
			admin.deleteAdminInfo(commandMap);
			auth.deleteAuthInfoById(userId);
			JspMaker jspmaker = new JspMaker();
			jspmaker.deleteJspFile(root, userId);
		}

		return "redirect:../admin/adminmng_list.do";
	}

}
